import { ref } from 'vue';
import axios from 'axios';

const soilData = ref<{ [key: string]: number }>({
    '土壤含水率': 0,
    '土壤电导率': 0,
    '土壤温度': 0,
    '土壤氮含量': 0,
    '土壤磷含量': 0,
    '土壤钾含量': 0,
    '土壤PH值': 0,
});

const environmentData = ref<{ [key: string]: number }>({
    '空气温度': 0,
    '空气相对湿度': 0,
    '二氧化碳': 0,
    '光照度': 0,
});

const photoUrl = ref<string | null>(null);
const photoLoading = ref<boolean>(true);
const cameraToken = ref<string | null>(null); // 新增：用于存储 cameraToken

// 获取所有传感器数据
const fetchAllData = async () => {
    try {
        const response = await axios.get('http://localhost:8080/api/sensor/soil-data');
        response.data.forEach((item: { name: string; value: number }) => {
            if (item.name.includes('土壤')) {
                soilData.value[item.name] = item.value;
            } else {
                environmentData.value[item.name] = item.value;
            }
        });
    } catch (error) {
        console.error('获取数据失败：', error);
    }
};

// 获取照片
const fetchPhoto = async () => {
    try {
        const response = await axios.get('http://localhost:8080/api/data/camera/L29334649');
        photoUrl.value = response.data;
    } catch (error) {
        console.error('获取照片失败：', error);
    } finally {
        photoLoading.value = false;
    }
};

// 新增：获取 cameraToken
const fetchCameraToken = async () => {
    try {
        const response = await axios.get('http://localhost:8080/api/token/camera');
        cameraToken.value = response.data.token; // 假设返回的数据结构为 { type: "camera", token: "xxx" }
    } catch (error) {
        console.error('获取 cameraToken 失败：', error);
    }
};

export const useFetchData = () => {
    return {
        soilData,
        environmentData,
        photoUrl,
        photoLoading,
        cameraToken, // 导出 cameraToken
        fetchAllData,
        fetchPhoto,
        fetchCameraToken, // 导出 fetchCameraToken 方法
    };
};